from py_mysql import Connect
from datetime import datetime


def new_input(func, text):
    result = input(f"--> 请输入{func}的{text}: ").strip()
    while True:
        if result == "":
            result = input('\n--> 不能为空, 请重新输入: ').strip()
        else:
            return result


def blog_input():
    print("--> 请输入内容(输入'endendend'后结束写作): ")
    result = []
    while True:
        data = input()
        if data == "endendend":
            return '\n'.join(result)
        result.append(data)


def register():
    while True:
        quit_reg = input("--> 如果要退出注册请输入Q/q, 任意键继续: ").strip()
        if quit_reg.upper() == 'Q':
            break

        with Connect() as obj:
            username = new_input('注册', "用户")
            check_sql = "select * from users where username = %(username)s"
            ret = obj.fetch_one(check_sql, username=username)
            if ret:
                print("--> 用户已存在, 请直接登录或者重新注册新用户")
                continue

            nickname = new_input('注册', "昵称")
            password = new_input('注册', "密码")
            email = new_input('注册', "邮箱")
            phone = new_input('注册', "手机")

            dic = {'username': username, 'nickname': nickname, 'password': password, 'email': email, 'phone': phone}
            sql = "insert into users (username, nickname, password, email, phone) values " \
                  "(%(username)s,%(nickname)s,%(password)s,%(email)s,%(phone)s)"
            obj.exec(sql, **dic)


def blog_write():
    title = new_input("博客", '标题')
    content = blog_input()
    with Connect() as obj:
        dic = {'title': title, 'content': content, 'date': str(datetime.now())}
        sql = "insert into articles (title, content, date) values " \
              "(%(title)s,%(content)s,%(date)s)"
        obj.exec(sql, **dic)


def view_detail(number, obj, username):
    count = 0
    print("--> 浏览博客内容如下(一页内容3篇博客)")
    while count < number:
        sql = f"""select articles.*, comment.评论数, liket.点赞数, liket.点踩数 from articles 
left join (select comment_title, count(1) 评论数 from comments group by comment_title) as comment 
on articles.title = comment.comment_title
left join (select blog_title, sum(likenum) 点赞数, sum(dislikenum) 点踩数 from liketable group by blog_title) as liket 
on articles.title = liket.blog_title limit {count},3;"""

        # result = obj.fetch_all(f"select * from articles limit {count},3")
        result = obj.fetch_all(sql)
        for _ in result:
            print(_)

        decision = input("请根据'articleid'选择要浏览的博客, 翻页请按任意键, 退出请按'q/Q: ").strip()
        if decision.upper() == "Q":
            break

        if not decision.isdecimal():
            count += 3
            continue

        if int(decision) > (count + 3):
            print("--> 'articleid'不在范围内")
            continue

        resultNew = obj.fetch_one(f"select * from articles where articleid = %(decision)s", decision=int(decision))
        # print(resultNew)
        sql = 'update articles set 阅读数=%(阅读数)s where articleid = %(articleid)s'
        obj.exec(sql, 阅读数=(resultNew['阅读数'] + 1), articleid=int(decision))

        commentNew = obj.fetch_all(f"select comment from comments where comment_title = %(title)s",
                                   title=resultNew['title'])


        print("--> 你要浏览的博客内容为:")
        print("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓")
        print(resultNew['content'])
        print("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑")

        print("--> 你要浏览的评论内容为:")
        print("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓")
        for _ in commentNew:
            print(_['comment'])
            print('--------------------')
        print("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑")

        print('--> 请输入你的评论(输入为空表示不评论)')

        comment = blog_input()
        if comment != "":
            sql = 'insert into comments (comment_title, comment) values(%(comment_title)s, %(comment)s)'
            obj.exec(sql, comment_title=resultNew['title'], comment=comment)

        like = input("请输入'1'点赞或者'2'点踩: ").strip()

        if like == '1':
            count = 0
            sql = "select * from liketable where blog_title = %(blog_title)s and user=%(user)s"
            check = obj.fetch_one(sql, blog_title=resultNew['title'], user=username)
            if check:
                sql = "update liketable set likenum=1, dislikenum=0 where blog_title = %(blog_title)s"
                obj.exec(sql, blog_title=resultNew['title'])
                continue
            else:
                sql = 'insert into liketable (blog_title, user, likenum, dislikenum) values (%(blog_title)s, %(user)s, %(like)s, %(dislike)s)'
                obj.exec(sql, blog_title=resultNew['title'], user=username, like=1, dislike=0)
                continue

        if like == '2':
            count = 0
            sql = "select * from liketable where blog_title = %(blog_title)s and user=%(user)s "
            check = obj.fetch_one(sql, blog_title=resultNew['title'], user=username)
            if check:
                sql = "update liketable set likenum=0, dislikenum=1 where blog_title = %(blog_title)s"
                obj.exec(sql, blog_title=resultNew['title'])
                continue
            else:
                sql = 'insert into liketable (blog_title, user, likenum, dislikenum) values (%(blog_title)s, %(user)s, %(like)s, %(dislike)s)'
                obj.exec(sql, blog_title=resultNew['title'], user=username, like=0, dislike=1)
                continue
        count += 3


def blog_view(username):
    with Connect() as obj:
        artical_num = obj.fetch_one('select count(1) from articles')
        # print(artical_num)
        view_detail(artical_num['count(1)'], obj, username)


def login():
    while True:
        quit_login = input("--> 如果要退出登录请输入Q/q, 任意键继续: ").strip()
        if quit_login.upper() == 'Q':
            break

        with Connect() as obj:
            username = new_input('登录', "用户")
            password = new_input('登录', "密码")
            check_sql = "select * from users where username = %(username)s and password = %(password)s"
            ret = obj.fetch_one(check_sql, username=username, password=password)
            if not ret:
                print("--> 登录失败, 请重新登录")
                continue
            else:
                print("--> 登录成功")
                menu = """--> 请选择要使用的功能...
--> [1] 输入'1'写博客...
--> [2] 输入'2'浏览博客...
--> [q/Q] 输入'Q/q'退出程序...
--> 请输入: """
                while True:
                    input_result = input(menu).strip()
                    if input_result.upper() == "Q":
                        break

                    if input_result == '1':
                        blog_write()

                    if input_result == '2':
                        blog_view(username)


def run():
    print("--> 欢迎使用路飞学城博客系统")
    menu = """--> 请选择要使用的功能...
--> [1] 输入'1'注册用户...
--> [2] 输入'2'登录用户...
--> [q/Q] 输入'Q/q'退出程序...
--> 请输入: """

    while True:
        input_result = input(menu).strip()
        if input_result.upper() == "Q":
            print("--> 程序结束, 欢迎再次使用...")
            break

        if input_result == '1':
            register()

        if input_result == '2':
            login()


if __name__ == "__main__":
    run()
